<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>活动管理</el-breadcrumb-item>
      <el-breadcrumb-item>活动列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片试图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList()">
            <el-button slot="append" @click="getUserList()" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUser = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="userList" border stripe>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>

        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChanged(scope.row)"
              active-color="#13ce66"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="editUserBtn(scope.row.id)"
              size="mini"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              @click="removeUserById(scope.row)"
              icon="el-icon-delete"
              size="mini"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button
                type="warning"
                @click="setRole(scope.row)"
                icon="el-icon-setting"
                size="mini"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog title="添加用户" :visible.sync="addUser" width="50%" @close="addUserClose">
      <!-- 内容主体区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUser = false">取 消</el-button>
        <el-button type="primary" @click="addUserBtn">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户的对话框 -->
    <el-dialog title="修改用户" :visible.sync="editUser" width="50%" @close="editUserClose">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editUser = false">取 消</el-button>
        <el-button type="primary" @click="confirmEditUserBtn(editForm.id)">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 分配角色的对话框 -->
    <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="50%">
      <div>
        <p>当前的用户:{{userInfo.username}}</p>
        <p>当前的角色:{{userInfo.role_name}}</p>
        <p>
          分配新角色:
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;

      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb();
      }

      cb(new Error("请输入合法的邮箱"));
    };

    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;

      if (regMobile.test(value)) {
        return cb();
      }

      cb(new Error("请输入合法的手机号"));
    };

    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 5
      },
      userList: [],
      total: 0,
      //   控制添加用户对话框的显示与隐藏
      addUser: false,
      // 控制修改用户对话框的显示与隐藏
      editUser: false,
      // 控制分配角色对话框的显示与隐藏
      setRoleDialogVisible: false,
      // 需要被分配角色的用户信息
      userInfo: {},
      // 获取到的所有角色列表
      rolesList: [],
      // 已选中的角色id值
      selectedRoleId: "",
      //   添加用户的表单数据
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      editForm: {},
      //  添加表单的验证规则对象
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用户名的长度在3~10个字符之间",
            trigger: "blur"
          }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "密码的长度在6~15个字符之间",
            trigger: "blur"
          }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            validator: checkEmail,
            trigger: "blur"
          }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            validator: checkMobile,
            trigger: "blur"
          }
        ]
      },
      editFormRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            validator: checkEmail,
            trigger: "blur"
          }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            validator: checkMobile,
            trigger: "blur"
          }
        ]
      }
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    getUserList() {
      this.$http.get("users", { params: this.queryInfo }).then(res => {
        var res = res.data;
        if (res.meta.status !== 200) {
          return this.$message.error("获取用户列表失败");
        }
        this.userList = res.data.users;
        this.total = res.data.total;
      });
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      console.log(newSize);
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newSize) {
      console.log(newSize);
      this.queryInfo.pagenum = newSize;
      this.getUserList();
    },
    // 监听switch开关的改变
    userStateChanged(data) {
      this.$http.put(`users/${data.id}/state/${data.mg_state}`).then(res => {
        var res = res.data;
        if (res.meta.status !== 200) {
          data.mg_state = !data.mg_state;
          return this.$message.error("更新用户状态失败");
        }
        this.$message.success("更新用户状态成功");
      });
    },
    // 监听用户对话框的关闭事件
    addUserClose() {
      this.$refs.addFormRef.resetFields();
    },
    // 确认添加按钮的监听
    addUserBtn() {
      // validate进行表单的规则验证
      this.$refs.addFormRef.validate(valid => {
        // this.addUser = false;
        if (!valid) return;
        this.$http.post("users", this.addForm).then(res => {
          var res = res.data;
          if (res.meta.status !== 201) {
            this.$message.error("添加用户失败");
          }

          this.$message.success("添加用户成功");
          // 隐藏添加用户的弹出框
          this.addUser = false;
          // 重新获取用户列表
          this.getUserList();
        });
      });
    },
    // 展示编辑用户的对话框
    editUserBtn(id) {
      this.editUser = true;
      this.$http.get("users/" + id).then(res => {
        var res = res.data;
        if (res.meta.status !== 200) {
          return this.$message.error("获取用户数据失败");
        }
        this.editForm = res.data;
        this.editUser = true;
      });
    },
    // 监听修改用户对话框的关闭事件
    editUserClose() {
      this.$refs.editFormRef.resetFields();
    },
    // 监听确认修改按钮
    confirmEditUserBtn(id) {
      // validate进行表单的规则验证
      this.$refs.editFormRef.validate(valid => {
        // 校验不通过直接返回
        if (!valid) return;
        this.$http
          .put("users/" + id, {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          })
          .then(res => {
            var res = res.data;
            if (res.meta.status !== 200) {
              return this.$message.error("更新用户信息失败");
            }
            this.$message.success("更新用户信息成功");
            // 隐藏弹出的修改用户对话框
            this.editUser = false;
            // 重新获取用户列表
            this.getUserList();
          });
      });
    },
    // 删除用户按钮的监听
    removeUserById(data) {
      // 提示用户是否确认删除
      this.$confirm(
        "此操作将永久删除用户:" + data.username + ", 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(res => {
          this.$http.delete("users/" + data.id).then(res => {
            var res = res.data;
            this.$message.success(res.meta.msg);

            // 重新获取用户列表数据
            this.getUserList();
          });
        })
        .catch(err => {
          this.$message.info("取消删除");
        });
    },
    // 分配角色按钮的监听
    setRole(userInfo) {
      this.selectedRoleId = "";
      this.userInfo = userInfo;
      this.$http.get("roles").then(res => {
        var res = res.data;
        if (res.meta.status !== 200) {
          return this.$message.error("获取角色列表失败!");
        }

        this.rolesList = res.data;
      });
      this.setRoleDialogVisible = true;
    },
    // 确定分配角色按钮的监听
    saveRoleInfo() {
      if (!this.selectedRoleId) {
        return this.$message.error("请选择要分配的角色");
      }

      this.$http
        .put(`users/${this.userInfo.id}/role`, {
          rid: this.selectedRoleId
        })
        .then(res => {
          var res = res.data;
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg);
          }

          this.$message.success(res.meta.msg);
          this.setRoleDialogVisible = false;
          this.getUserList();
        });
    }
  }
};
</script>

<style lang="scss" scoped>
</style>